import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { listData, delData, getData, saveData, findMaxSort } from '@/api/system/dict/data'
import { useState } from "react";
import { ModalForm } from "@ant-design/pro-components";
import DictDataForm from "./modules/dictDataForm";
import { App, Button, Divider, Flex, Space, Table } from "antd";
import { parseTime } from "../../../utils";
import PropTypes from "prop-types";
import { PlusOutlined, ExclamationCircleFilled, RedoOutlined } from '@ant-design/icons';
const DictDataIndex = ({ dictType, dictId, title = '子表' }) => {
  const { message, modal } = App.useApp();
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 100,
    dictName: undefined,
    dictType: dictType,
    status: undefined
  })
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const columns = [
    {
      title: '字典名称',
      dataIndex: 'dictLabel',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '字典排序',
      dataIndex: 'dictSort',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '描述',
      dataIndex: 'remark',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      align: 'center',
      render: (_, { createTime }) => (
        <>
          {parseTime(createTime)}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '10%',
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改【${title}】子表数据`}
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            request={() => {
              return getData(record.id).then(res => {
                return { ...res.data }
              })
            }}
            grid={true}
          >
            <DictDataForm dataId={record.id} dictType={dictType} />
          </ModalForm>

          {
            record.parentId != 0 && <Divider type="vertical" />
          }
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-dict-listData', searchParams],
    queryFn: () => {
      return listData({
        ...searchParams,
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }


  const handleSave = (values) => {
    return saveData({ ...values, dictCode: values.dictType }).then(() => {
      refetch()
      if (values.id) {
        message.success('修改成功')
      } else {
        message.success('新增成功')
      }
      return true
    })
  }

  const deleteConfirm = (row) => {
    const dictIds = row.id || selectedRowKeys
    const dictNames = row.dictLabel || selectedRows.map(d => d.dictLabel)
    modal.confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: `当前选中字典编码为"${dictNames}"的数据`,
      autoFocusButton: null,
      onOk() {
        return delData(dictIds)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  return <div style={{ padding: '8px', marginLeft: '48px' }}>
    <Flex align="center" justify="space-between">
      <div className="table_title" style={{ fontWeight: 'bold' }}>{title}</div>
      <Space>
        <ModalForm
          trigger={<Button type="primary" icon={<PlusOutlined />}>新增</Button>}
          title="添加字典类型"
          modalProps={{ destroyOnClose: true }}
          onFinish={handleSave}
          grid={true}
          request={() => {
            return findMaxSort(dictType).then(res => {
              return { dictType: dictType, dictSort: res.data, status: '0' }
            })
          }}
        >
          <DictDataForm dictType={dictType} />
        </ModalForm>
        {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
        <Button type="text" icon={<RedoOutlined />} onClick={refetch}></Button>
      </Space>
    </Flex>
    <Table
      rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
      columns={columns}
      rowKey={(record) => record.id}
      loading={isFetching}
      dataSource={tableData?.list}
      pagination={false}
    />
  </div>;
}
DictDataIndex.propTypes = {
  dictType: PropTypes.string.isRequired,
  dictId: PropTypes.string.isRequired,
  title: PropTypes.string
}

export default DictDataIndex;